#! /usr/bin/env python3
# ! coding:utf-8
#

import requests
import time
from bs4 import BeautifulSoup
import re
import os


class Res_Cdd(object):

    def __init__(self, datas):
        self.post_datas = datas
        self.post_url = ""
        self.session = requests.Session()
        self.session.headers.update({
            "User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 13_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 MicroMessenger/7.0.12(0x17000c30) NetType/WIFI Language/zh_CN",
            "Host": "xjdwsy.cn",
            "Connection": "keep-alive",
            "Sec-Fetch-Site": "same-origin",
            "Origin": "",
            "Referer": "",

        })

    '''
        获取验证码数据
    '''

    def get_capctha(self, url):
        im = self.session.get(url).content
        with open("验证码.png",'wb') as file:
            file.write(im)

    '''
        获取token值
    '''

    def get_token(self, url):
        html = self.session.get(url)  # 访问登记信息界面
        soup = BeautifulSoup(html.text, "html.parser")
        while soup.find("div", {"class": "alert alert-danger"}):  # 检测是否可以预定
            html = self.session.get(url)  # 访问登记信息界面
            soup = BeautifulSoup(html.text, "html.parser")
            print("[{}] {}".format(time.strftime("%Y-%m-%d %H:%M:%S"),
                                   soup.find("div", {"class": "alert alert-danger"}).text))
            time.sleep(1)

        return soup.find("input", {"name": "_token"})["value"]

    '''
        主函数
    '''

    def main(self):

        for post_data in post_datas:  # 遍历所有客户信息
            url = "" + post_data["doctor_id"]
            html = self.session.get(url)  # 访问登记信息界面

            post_data["_token"] = self.get_token("")
            self.get_capctha("")
            captcha = input("验证码:")
            if len(captcha) != 4:
                raise Exception("验证码长度不正确！")
            post_data["captcha"] = captcha
            html = self.session.post(self.post_url, data=post_data)
            with open('1.png','wb') as file:
                file.write(html.content)
            soup = BeautifulSoup(html.text, "html.parser")

            if html.status_code == 200 and re.search("预约凭证", html.text):
                with open(f"{os.path.split(__file__)[0] + '/' + post_data['patient_name']}.html", "w+") as f:
                    f.write(html.content.decode('utf-8'))
                print("[{}] {}预定成功！".format(time.strftime("%Y-%m-%d %H:%M"), post_data['patient_name']))
            elif html.status_code == 200 and re.search("验证码错误", html.text):
                self.cjy.ReportError(captcha['pic_id'])
                print("[{}] captchaId:{} 报错成功！".format(time.strftime("%Y-%m-%d %H:%M"), captcha['pic_id']))
                count += 1
            elif html.status_code == 200 and re.search("8小时内不能重复预约", html.text):
                print("[{}] 8小时内不能重复预约！".format(time.strftime("%Y-%m-%d %H:%M")))
            else:
                print("[{}] {}".format(time.strftime("%Y-%m-%d %H:%M"),soup.find("div", {"class": "alert alert-danger"})))
                print(html.text)


if __name__ == "__main__":

    post_datas = [{
        "_token": "",
        "captcha": "",
        "doctor_id": "",
        "patient_name": "",
        "patient_sex": "",
        "patient_idcard": "",
        "patient_phone": ""}
    ]
    res = Res_Cdd(post_datas)
    res.main()
    # for i in range(10):
    #     print(res.get_capctha(""))